<?php
/**
 * 
 * 
 * modifiedOn 2012-03-28  oushunbao 
 * 		允许配置文件中强制设定from_email, from_name
 */
class sendEmail{            //发送email

	private $emailFormatObject;             //定义email格式对象
	private $emailXML;                   //定义emailXML
	private $defaultAccountId = "default_account_id";    //定义默认的计算id 
	 
	function sendEmail($emailXML){   //构造方法
		$this->emailFormatObject=new emailFormat();//实例化一个emailFormat类

		$this->emailFormatObject->parseEmail($emailXML);    
		$this->emailXML = $emailXML;           //获得email的xml内容
	}
	 
	function toSend(){                      //toSend方法
		$accountId = "";               //初始化计算的id
		if (isset($this->emailFormatObject->sending_account_id)){   //如果id 被设定了
			$accountId = (string) $this->emailFormatObject->sending_account_id;//将accountId设定为传来的sending_account_id
		}
		if (trim($accountId) == "" && isset($this->emailFormatObject->email_list_id)){     //
			$accountId = (string) $this->emailFormatObject->email_list_id;
		}
		if (trim($accountId) == "") $accountId = $this->defaultAccountId;

		$sendAccountInfo=$this->getSendingAccount($accountId);
		if (count($sendAccountInfo) == 0){
			echo "  not find the account:[{$accountId}], autoly switch to [{$this->defaultAccountId}]. ";
			$accountId = $this->defaultAccountId;
			$sendAccountInfo=$this->getSendingAccount($accountId);
		}
		$sendAccount=$sendAccountInfo['user_name'];
		$sendPassword=$sendAccountInfo['password'];
		$smtpHost=$sendAccountInfo['host'];
		$smtpPort=$sendAccountInfo['port'];
		$smtpAuth = $sendAccountInfo['smtpAuth'];
		$secretSend = array();
		$countToSecret = 0;
		if($sendAccountInfo['copy_to']<>''){
			if(is_array(explode(',',$sendAccountInfo['copy_to'])))
			foreach(explode(',',$sendAccountInfo['copy_to']) as $copyTo)
			{
				$count_to_name=count($this->emailFormatObject->to_list->to_info);
				$this->emailFormatObject->to_list->to_info[$count_to_name]->to_name="copyer";
				$this->emailFormatObject->to_list->to_info[$count_to_name]->to_email=trim($copyTo);
			}

		}
		if($sendAccountInfo['secret_copy']<>''){
			if(is_array(explode(',',$sendAccountInfo['secret_copy'])))
			foreach(explode(',',$sendAccountInfo['secret_copy']) as $secretCopy)
			{
				$secretSend[$countToSecret] = array('to_name'=>'','to_email'=>'');
				$secretSend[$countToSecret]['to_name']="secretCopyer";
				$secretSend[$countToSecret]['to_email']=trim($secretCopy);
				$countToSecret++;
			}

		}
		$sendFlage=array();
		$mailObjcet = new PHPMailer();
		$mailObjcet->Host =(string)$smtpHost;
		$mailObjcet->Port = (int)$smtpPort;
		$mailObjcet->Mailer = 'smtp';
		$mailObjcet->CharSet = "UTF-8";
		$mailObjcet->IsHTML(true);

		if($mailObjcet->Port != 25) $mailObjcet->SMTPSecure = "ssl";	
		
		// 判断是否要认证 
		if ($smtpAuth === "false"){
			$mailObjcet->SMTPAuth = false;
		}else{
			$mailObjcet->SMTPAuth = true;
			$mailObjcet->Username =(string)$sendAccount;
			$mailObjcet->Password =(string)$sendPassword;
		}
		
		// 配置文件中可以强制更改 from email 和 from name
		if (isset($sendAccountInfo['from_email']) && $sendAccountInfo['from_email']) 
			$mailObjcet->From = $sendAccountInfo['from_email'];
		else $mailObjcet->From = (string)$this->emailFormatObject->from_email;
		if (isset($sendAccountInfo['from_name']) && $sendAccountInfo['from_name']) 
			$mailObjcet->FromName = $sendAccountInfo['from_name'];
		else $mailObjcet->FromName =(string) $this->emailFormatObject->from_name;

		// check fromEmail = toEmail, if yes, change toEmail.
		$fromEmail = strtolower($mailObjcet->From);
		foreach ($this->emailFormatObject->to_list->to_info as $toIndex => $toInfo){
			$toEmail = strtolower((string)$toInfo->to_email);
			if ($toEmail == $fromEmail){
				$toInfo->to_email = "repeat_" . $toEmail;
				echo " fromEmail({$fromEmail}) can not equal toEmail({$toEmail}), so ignore it.\n";
			}
		}

		$mailObjcet->AddReplyTo((string)$this->emailFormatObject->reply_to_email,(string)$this->emailFormatObject->reply_to_name);
		foreach($this->emailFormatObject->to_list as $to_info)
		{
			if((string)$to_info->to_email=='')continue;
			$mailObjcet->AddAddress((string)$to_info->to_email,'');
		}
		foreach($secretSend as $to_secret)
		{
			if((string)$to_secret->to_email=='')continue;
			$mailObjcet->AddBCC((string)$to_secret->to_email,'');
		}
		$mailObjcet->Subject = (string)$this->emailFormatObject->email_subject;
		$mailObjcet->Body = (string)$this->emailFormatObject->email_content;
		
		$basePath = dirname($this->emailXML) . "/";
		foreach($this->emailFormatObject->email_attachments as $attachment){
			$mailObjcet->AddAttachment( $basePath . $attachment);
		}
		$sendFlage[]=$mailObjcet->send();
		if (trim($mailObjcet->ErrorInfo) != "") echo " Error when send: ". $mailObjcet->ErrorInfo. "\n";
		
		return $sendFlage;
	}
	 
	function getSendingAccount($accountId){

			$xmlParser=simplexml_load_file(dirname(__FILE__)."/sendEmailAccount.xml");
			$sendAccountInfo=array();
			foreach ($xmlParser as $value ){
	
				if((string)$value->account_id== $accountId ){
					$sendAccountInfo['account_id']=$value->account_id;
					$sendAccountInfo['copy_to']=$value->copy_to;
					$sendAccountInfo['secret_copy']=$value->secret_copy;
					$sendAccountInfo['smtpAuth'] = "true";
					if (isset($value->smtpAuth) && strtolower(trim($value->smtpAuth)) == "false"){
						$sendAccountInfo['smtpAuth'] = "false";
					}
					$sendAccountInfo['from_email']=$value->from_email;
					$sendAccountInfo['from_name']=$value->from_name;
					if(isset($value->send_email_host_group) ){//如果存在组id则取组中的随机一个
						
						$groupId=$value->send_email_host_group;
						
						$xmlParserGroup=simplexml_load_file(dirname(__FILE__)."/sendEmailAccountGroupChoice.xml");//获得另一个XML中的参数
						foreach ($xmlParserGroup as $groupValue){
							if($groupValue['group_id']==(string)$groupId){
								$groupLength=count($groupValue);
								$randChoiceNumber=rand(1,$groupLength);
							//
		//					echo "groupId : " . $groupId. "| number : " . $randChoiceNumber . "\n";
								
								foreach($groupValue as $subValue){
									
									if($subValue->email_account_info_sign==$randChoiceNumber){
									
									    $sendAccountInfo['host']=$subValue->host;
										$sendAccountInfo['user_name']=$subValue->user_name;
										$sendAccountInfo['password']=$subValue->password;
										$sendAccountInfo['port']=$subValue->port;
										$sendAccountInfo['from_email']=$subValue->from_email;
					                                        $sendAccountInfo['from_name']=$subValue->from_name;								
										break;
									}	
							    }		
							}
						}
					}else{                              //如果没有设定组别的id就用原来的
						$sendAccountInfo['host']=$value->host;
						$sendAccountInfo['user_name']=$value->user_name;
						$sendAccountInfo['password']=$value->password;
						$sendAccountInfo['port']=$value->port;
                      
						
					}
					break;
				}
			}
		//print_r($sendAccountInfo); 
			return  $sendAccountInfo;
	}
	 
	 
}


?>
